package net.jsoft.platform.oauth2.service.impl.weibo;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import net.jsoft.platform.core.util.http.HttpUtils;
import net.jsoft.platform.oauth2.service.IThirdPartyLoginService;
import net.jsoft.platform.oauth2.util.ThirdPartyConstant;
import net.sf.json.JSONObject;

@Service("weiboService")
public class WeiboLoginSeriviceImpl implements IThirdPartyLoginService
{
    @Autowired
    private ThirdPartyConstant tpc;

    @Override
    public String getUser(String code)
    {
        String id = null;
        Map<String, String> map = new HashMap<String, String>();
        map.put("client_id", tpc.getWeiboClientId());
        map.put("client_secret", tpc.getWeiboClientSecret());
        map.put("grant_type", "authorization_code");
        map.put("code", code);
        map.put("redirect_uri", tpc.getWeiboRedirectUri());

        String result = null;
        try
        {
            String url = tpc.getWeiboAccessTokenUri();
            result = HttpUtils.post(url, map, "utf-8");
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        if (result != null && result.indexOf("access_token") > -1)
        {
            JSONObject obj = JSONObject.fromObject(result);
            String accessToken = obj.get("access_token") + "";
            map = new HashMap<String, String>();
            map.put("access_token", accessToken);
            String s = HttpUtils.post(tpc.getWeiboUserInfoUri(), map, "utf-8");
            obj = JSONObject.fromObject(s);
            id = obj.get("uid") + "";

        }
        return id;
    }

}
